import React,{FC,ReactNode,useEffect,useState,useRef,forwardRef,useImperativeHandle} from 'react';

interface Iprops{
    children:ReactNode;
    css:string;
    list:any[];
    ref:any
}

const LazyImage:FC<Iprops> = forwardRef(function(props,ref){

    let [clinetHeight,setclientHeight] = useState<number>(0);

    let scrollBox = useRef<HTMLDivElement>(null);

    let imgs:HTMLImageElement[] = [];

    //1.获取所有的imgs  //2.获取盒子的scrollTop值  

    const scroll = () => {
        imgs.forEach((img:HTMLImageElement) => {
            if(((scrollBox.current as HTMLDivElement).scrollTop + clinetHeight) > img.offsetTop){
                //加载图片
                // console.log("===",img)
                let dataSrc:string = img.getAttribute("data-src") as string;
                img.setAttribute("src",dataSrc)
            }
        })
    }

    useEffect(() => {
        let height = (scrollBox.current as HTMLDivElement).clientHeight;
        setclientHeight(height);
    },[])

    useEffect(() => {
        (scrollBox.current as HTMLDivElement).addEventListener('scroll',scroll);
        console.log((scrollBox.current as HTMLDivElement))
        // eslint-disable-next-line react-hooks/exhaustive-deps
        imgs = [...(scrollBox.current as HTMLDivElement).querySelectorAll("img")];
        scroll();
    }, [props.list])

    useImperativeHandle(ref,() => ({
        scrollToElement(index:number){
            let divs = (scrollBox.current as HTMLDivElement).querySelectorAll("div");
            (scrollBox.current as HTMLDivElement).scrollTop = divs[index].offsetTop;
        }
    }))

    return <div className={props.css} ref={scrollBox}>
        {props.children}
    </div>
})

export default LazyImage

